import React, { forwardRef, PureComponent } from 'react'
import { Collapse, Empty, Form, Input, message, Modal, Popconfirm, Radio, Select, Spin, Table } from 'antd'
import { DeleteOutlined, RightOutlined } from '@ant-design/icons'
import { connect } from '@umijs/max'
import { v4 } from 'uuid'
import { ProTable, ProTableOptions } from '@/components'
import {
  getDatabasesByDsType,
  getHbaseColumnFamilyNames,
  getSinkDetail,
  getTableFields,
  getTables,
  getTopicAndColumns,
  previewData,
  previewKafkaData,
  saveSink
} from '../../../api'
import styles from './index.less'

const { Panel } = Collapse
const { Option } = Select
const { TextArea } = Input

const SourceOptions = ['Kafka', 'MySQL', 'HBase', 'Hive']

class Result extends PureComponent {
  constructor(props) {
    super(props)
    this.state = {
      spreadSta: false,
      taskNode: {},
      previewDatas: {
        columns: [],
        data: [],
      },
      allValues: {},
      dataSourcesKafka: [], // 数据源
      previewKafkaDatas: [],
      kafkaColumns: (index) => {
        const { sourceTableData } = this.state
        const fields = sourceTableData[index].fields
        const key = sourceTableData[index].key
        return [
          {
            title: '字段',
            dataIndex: 'field',
            width: '35%',
            key: 'field',
            render: (text, record) => (
              <div>
                {fields ? (
                  <Select
                    value={text}
                    autoComplete="off"
                    placeholder="请选择类型"
                    onChange={(value, e) => {
                      record.field = value
                      record.type = e.props.type
                      this.forceUpdate()
                      this.saveData()
                    }}
                    showSearch
                    filterOption={(inputValue, option) => (
                      option.props.children
                        .toUpperCase()
                        .indexOf(inputValue.toUpperCase()) !== -1
                    )}
                  >
                    {fields.map((item) => (
                      <Option
                        title={item.fieldName}
                        label={item.fieldName}
                        type={item.fieldType}
                        key={item.fieldName}
                        value={item.fieldName}
                      >
                        {item.fieldName}
                      </Option>
                    ))}
                  </Select>
                ) : (
                  <Input
                    onChange={(e) => {
                      record.field = e.target.value
                      this.forceUpdate()
                    }}
                    onBlur={() => {
                      this.saveData()
                    }}
                    value={text}
                  />
                )}
              </div>
            ),
          },
          {
            title: '类型',
            dataIndex: 'type',
            width: '35%',
            key: 'type',
            render: (text, record) => (
              <div>
                <Input
                  onChange={(e) => {
                    record.type = e.target.value
                    this.forceUpdate()
                  }}
                  onBlur={() => {
                    this.saveData()
                  }}
                  value={text}
                />
              </div>
            ),
          },
          {
            title: '操作',
            dataIndex: 'operation',
            width: '30%',
            key: 'operation',
            render: (text, record, k) => (
              <ProTableOptions>
                {[
                  <span onClick={this.deleteField.bind(this, k, key)}>
                    删除
                  </span>,
                ]}
              </ProTableOptions>
            ),
          },
        ]
      },
      HiveColumns: (index) => [
        {
          title: '字段',
          dataIndex: 'fieldName',
          width: '35%',
          key: 'field',
        },
        {
          title: '类型',
          dataIndex: 'fieldType',
          width: '35%',
          key: 'type',
        },
        {
          title: '分区',
          dataIndex: 'isPartition',
          width: '30%',
          key: 'isPartition',
          render: (text, record) => (
            <span>{text == 1 ? '是' : '否'}</span>
          ),
        },
      ],
      // 单一数据
      sourceTableData: [],
    }
    this.resultForm = React.createRef()
    this.time = null
  }

  // 进入工作流页面，第一次点击工作流程目标，此时页面还未加载
  componentDidMount() {
    this.getDatabasesByDsType('Kafka')
    this.getDatabasesByDsType('MySQL')
    this.getDatabasesByDsType('HBase')
    this.getDatabasesByDsType('Hive')
    this.setState(
      {
        taskNode: this.props?.taskNode,
      },
      () => {
        this.getSinkDetail()
      },
    )
  }

  UNSAFE_componentWillUpdate(nextProps) {
    if (nextProps.taskNode != this.props.taskNode) {
      // eslint-disable-next-line react/no-will-update-set-state
      this.setState(
        {
          taskNode: nextProps.taskNode,
        },
        () => {
          this.getSinkDetail()
        },
      )
    }
  }

  /**
   * 获取源表配置
   */
  getSinkDetail = () => {
    getSinkDetail({ nodeId: this.state.taskNode.nodeId }).then((res) => {
      if (res.status === 200) {
        const sourceTableData = []
        const initDto = {}
        res.data.forEach((item, index) => {
          initDto[`dsId[${index}]`] = item.dsId
          initDto[`sourceType[${index}]`] = item.dsType
          initDto[`mappingTableName[${index}]`] = item.mappingTableName
          if (item.dsType === 'Kafka') {
            initDto[`offset[${index}]`] = item.kafkaSink.offset
            initDto[`topic[${index}]`] = item.kafkaSink.topic
          } else if (item.dsType === 'MySQL') {
            initDto[`dataMode[${index}]`] = item.jdbcSink.dataMode
            initDto[`primaryFields[${index}]`] = item.jdbcSink.primaryFields || []
            initDto[`tableName[${index}]`] = item.jdbcSink.tableName
            this.getTableFields(
              item.dsId,
              item.jdbcSink.tableName,
              index,
              item.dsType,
            )
          } else if (item.dsType === 'Hive') {
            initDto[`tableName[${index}]`] = item.hiveSinkDomain.tableName
            this.getTableFields(
              item.dsId,
              item.hiveSinkDomain.tableName,
              index,
              item.dsType,
              true,
            )
          } else if (item.dsType === 'HBase') {
            initDto[`dataMode[${index}]`] = item.hbaseSinkDomain.dataMode
            initDto[`primaryFields[${index}]`] = item.hbaseSinkDomain.primaryFields || []
            initDto[`tableName[${index}]`] = item.hbaseSinkDomain.tableName
            initDto[`rowKeyName[${index}]`] = item.rowKeyName
            initDto[`rowKeyType[${index}]`] = item.rowKeyType
            this.getHbaseColumnFamilyNames(
              item.dsId,
              item.hbaseSinkDomain.tableName,
              index,
              item.fieldList,
            )
          }
          sourceTableData.push({
            name: '结果表',
            key: v4(),
            topics: [],
            tableNames: [],
            fieldList: item.fieldList,
          })
          this.getTables(item.dsId, index)
        })

        this.setState(
          {
            sourceTableData,
            allValues: initDto,
          },
          () => {
            this.resultForm?.current?.setFieldsValue(initDto)
          },
        )
      }
    })
  }

  /**
   * 获取数据源
   */
  getDatabasesByDsType = dsType => {
    getDatabasesByDsType({
      dsType,
    }).then((res) => {
      if (res.status === 200) {
        this.setState({
          [`dataSources${dsType}`]: res.data,
        })
      }
    })
  }

  /**
   * 切换数据源
   * @param {number} 第几个数据源
   * @param {number} 第几个数据源
   */
  changeSourceType = (val, index) => {
    const { allValues } = this.state
    const sourceType = allValues[`sourceType[${index}]`]
    if (sourceType === 'Kafka') {
      this.getTopicAndColumns(val, index)
    } else if (sourceType === 'MySQL') {
      this.getTables(val, index)
    } else if (sourceType === 'HBase') {
      this.getTables(val, index)
    } else if (sourceType === 'Hive') {
      this.getTables(val, index)
    }
  }

  /**
   * 获取topic
   */
  getTopicAndColumns = (dsId, index) => {
    getTopicAndColumns({
      dsId,
    }).then((res) => {
      if (res.status === 200) {
        const { sourceTableData } = this.state
        if (sourceTableData) {
          sourceTableData[index].topics = res.data || []
          this.setState({
            sourceTableData: [...sourceTableData],
          })
        }
      }
    })
  }

  /**
   * 获取tables
   */
  getTables = (dsId, index) => {
    getTables({
      dsId,
      isPartition: 0,
    }).then((res) => {
      if (res.status === 200) {
        const { sourceTableData } = this.state
        sourceTableData[index].tableNames = res.data || []

        this.setState({
          sourceTableData: [...sourceTableData],
        })
      }
    })
  }

  /**
   * 获取mySql Oracle表字段信息
   */
  getTableFields = (dsId, tableName, index, type, bool) => {
    getTableFields({ dsId, tableName }).then((res) => {
      if (res.status === 200) {
        const { sourceTableData } = this.state
        type === 'Hive' ? sourceTableData[index].fieldList = res.data : null
        sourceTableData[index].fields = res.data
        this.setState({
          sourceTableData: [...sourceTableData],
        }, () => {
          if (type === 'Hive' && !bool) {
            this.saveData()
          }
        })
      }
    })
  }

  getHbaseColumnFamilyNames = (dsId, tableName, index, fieldList) => {
    getHbaseColumnFamilyNames({ dsId, tableName }).then((res) => {
      if (res.status === 200) {
        const { sourceTableData } = this.state
        sourceTableData[index].columnFamily = []
        const columnFamily = new Set()
        const columnFamilyArr = new Set()
        fieldList
          && fieldList.map((item) => {
            columnFamilyArr.add(item.columnFamily)
          })
        res.data
          && res.data.map((key) => {
            if (fieldList && fieldList.length && columnFamilyArr.has(key)) {
              fieldList.map((item) => {
                if (item.columnFamily == key) {
                  if (columnFamily.has(item.columnFamily)) {
                    sourceTableData[index].columnFamily.map((obj) => {
                      if (obj.columnFamily == item.columnFamily) {
                        item.field && item.type ? obj.fields.push(item) : null
                      }
                    })
                  } else {
                    columnFamily.add(key)
                    item.field && item.type
                      ? sourceTableData[index].columnFamily.push({
                        columnFamily: key,
                        fields: [
                          {
                            ...item,
                          },
                        ],
                      })
                      : null
                  }
                }
              })
            } else {
              sourceTableData[index].columnFamily.push({
                columnFamily: key,
                fields: [],
              })
            }
          })
        this.setState({
          sourceTableData: [...sourceTableData],
        })
      }
    })
  }

  /**
   * 数据表mysql/oracle预览
   */
  previewData = (dsId, tableName) => {
    this.setState({
      previewDataShow: true,
      confirmLoading: true,
    })
    previewData({
      dsId,
      tableName,
    }).then((res) => {
      if (res.status === 200) {
        const data = []
        const columns = []
        res.data.fieldNameList
          && res.data.fieldNameList.map((name, i) => {
            columns.push({
              title: name,
              dataIndex: name,
              key: name,
            })
          })
        res.data.dataList
          && res.data.dataList.map((arr, key) => {
            const dataObj = { key }
            res.data.fieldNameList
              && res.data.fieldNameList.map((name, i) => {
                dataObj[name] = arr[i]
              })
            data.push(dataObj)
          })
        this.setState({
          previewDatas: {
            columns,
            data,
          },
          confirmLoading: false,
        })
      } else {
        message.warning(res.msg)
        this.setState({
          confirmLoading: false,
        })
      }
    })
  };

  // eslint-disable-next-line react/no-unused-class-component-methods
  toggleResult = (spreadStaParams = undefined) => {
    if (!this.state.spreadSta) {
      this.getSinkDetail()
    }
    this.setState((prevState) => ({
      spreadSta: spreadStaParams !== undefined ? spreadStaParams : !prevState.spreadSta,
    }))
  };

  /**
   * 添加源表
   */
  addSourceTable = () => {
    const key = v4()
    const { sourceTableData } = this.state
    sourceTableData.push({
      name: '结果表',
      key,
      topics: [],
      tableNames: [],
      fieldList: [],
      fields: null,
    })
    this.setState({
      activeKeys: [key],
      sourceTableData: [...sourceTableData],
    })
  }

  /**
   * 删除数据源
   * @param {number} index
   */
  deleteItem = (index) => {
    const { sourceTableData } = this.state
    sourceTableData.splice(index, 1)

    this.setState(
      {
        sourceTableData: [...sourceTableData],
      },
      () => {
        this.saveData()
      },
    )
  }

  /**
   * 添加字段
   */
  addField = (index) => {
    const { sourceTableData } = this.state
    sourceTableData[index].fieldList.push({
      field: '',
      type: '',
    })

    this.setState({
      sourceTableData: [...sourceTableData],
    })
  };

  /**
   * 删除字段
   */
  deleteField = (index, key) => {
    const { sourceTableData } = this.state
    sourceTableData.forEach((item) => {
      if (item.key === key) {
        item.fieldList.splice(index, 1)
      }
    })
    this.setState(
      {
        sourceTableData: [...sourceTableData],
      },
      () => {
        this.saveData()
      },
    )
  }

  /**
   * 数据表Kafka预览
   */
  previewKafkaData = (dsId, topic) => {
    this.setState({
      kafkaDataShow: true,
      confirmLoading: true,
    })
    previewKafkaData({
      dsId,
      topic,
    }).then((res) => {
      if (res.status === 200) {
        this.setState({
          previewKafkaDatas: res.data,
        })
      } else {
        message.error(res.msg)
      }
      this.setState({
        confirmLoading: false,
      })
    })
  }

  /**
   * 实时保存
   */
  saveData = () => {
    this.resultForm?.current?.validateFields().then(fieldsValue => {
      const result = this.state.sourceTableData.map((item, index) => {
        const dto = {}
        dto.dsId = fieldsValue[`dsId[${index}]`]
        dto.mappingTableName = fieldsValue[`mappingTableName[${index}]`] || null

        dto.dsType = fieldsValue[`sourceType[${index}]`]
        if (dto.dsType === 'HBase') {
          dto.rowKeyName = fieldsValue[`rowKeyName[${index}]`]
          dto.rowKeyType = fieldsValue[`rowKeyType[${index}]`]
          dto.fieldList = []
          item.columnFamily.map((obj) => {
            obj.fields.map((field) => {
              dto.fieldList.push({
                field: field.field,
                type: field.type,
                columnFamily: obj.columnFamily,
              })
            })
          })
        } else if (dto.dsType === 'Hive') {
          dto.fieldList = item.fieldList.map((field) => ({
            field: field.fieldName,
            type: field.fieldType,
            isPartition: field.isPartition,
          }))
        } else {
          dto.fieldList = item.fieldList.map((field) => ({
            field: field.field,
            type: field.type,
          }))
        }

        // 判断是否是kafka
        if (dto.dsType === 'Kafka') {
          dto.kafkaSink = {
            topic: fieldsValue[`topic[${index}]`],
          }
        } else if (dto.dsType === 'HBase') {
          dto.hbaseSink = {
            tableName: fieldsValue[`tableName[${index}]`],
            dataMode: fieldsValue[`dataMode[${index}]`],
            primaryFields: fieldsValue[`primaryFields[${index}]`] || null,
          }
        } else if (dto.dsType === 'MySQL') {
          dto.jdbcSink = {
            tableName: fieldsValue[`tableName[${index}]`],
            dataMode: fieldsValue[`dataMode[${index}]`],
            primaryFields: fieldsValue[`primaryFields[${index}]`] || null,
          }
        } else if (dto.dsType === 'Hive') {
          dto.hiveSink = {
            tableName: fieldsValue[`tableName[${index}]`],
            dataMode: fieldsValue[`dataMode[${index}]`] || null,
            primaryFields: fieldsValue[`primaryFields[${index}]`] || null,
          }
        }
        return dto
      })
      saveSink({
        nodeId: this.state.taskNode?.nodeId,
        sinks: result,
      }).then((res) => {
        if (res.status === 200) {
          this.props.getTaskDetail()
        }
      })
    })
  }

  valuesChange = (value, allValues) => {
    this.setState({
      allValues,
    }, () => {
      clearTimeout(this.time)
      this.time = setTimeout(() => {
        this.saveData()
      }, 1000)
    })
  }

  render() {
    const {
      spreadSta, allValues, activeKeys, previewDataShow, kafkaDataShow, kafkaColumns, HiveColumns, sourceTableData, dataSourcesKafka, previewKafkaDatas, previewDatas,
    } = this.state
    return (
      <div className={`${styles.node_result} ${spreadSta ? styles.spread : ''}`}>
        <div className={styles.node_result_column}>
          结果表配置
          <i
            className={`iconfont icon-addition_fill ${styles.addition_fill}`}
            onClick={() => {
              this.addSourceTable()
            }}
          />
        </div>
        <Form
          layout="vertical"
          ref={this.resultForm}
          autoComplete="off"
          onValuesChange={this.valuesChange}
        >
          {sourceTableData && sourceTableData.length > 0 ? (
            <Collapse
              activeKey={activeKeys}
              onChange={(value) => {
                this.setState({
                  activeKeys: value,
                })
              }}
            >
              {sourceTableData.map((item, index) => (
                <Panel
                  key={item.key}
                  header={
                    <div className={styles.real_time_task_panel_table_header}>
                      <span>
                        {item.name}
                        {index + 1}
                        {allValues[`mappingTableName[${index}]`]
                          ? `(${allValues[`mappingTableName[${index}]`]})`
                          : ''}
                      </span>
                      <span className={styles.delete_icon}>
                        <Popconfirm
                          placement="topLeft"
                          title="确认要删除这个源表吗？"
                          onConfirm={() => {
                            this.deleteItem(index)
                          }}
                          okText="确定"
                          cancelText="取消"
                        >
                          <DeleteOutlined
                            onClick={(e) => {
                              e.stopPropagation()
                              e.preventDefault()
                            }}
                          />
                        </Popconfirm>
                        <RightOutlined />
                      </span>
                    </div>
                  }
                  forceRender
                  showArrow={false}
                >
                  <Form.Item
                    name={`sourceType[${index}]`}
                    rules={[
                      { required: true, message: '请选择类型' },
                    ]}
                    label="类型"
                  >
                    <Select
                      autoComplete="off"
                      placeholder="请选择类型"
                      onChange={() => {
                        const initDto = {}
                        console.log(this.resultForm)
                        initDto[`dsId[${index}]`] = undefined
                        initDto[`tableName[${index}]`] = undefined
                        this.resultForm?.current?.setFieldsValue(initDto)
                      }}
                    >
                      {SourceOptions.map((val) => (
                        <Option label={val} key={val} value={val}>
                          {val}
                        </Option>
                      ))}
                    </Select>
                  </Form.Item>
                  <Form.Item
                    name={`dsId[${index}]`}
                    rules={[
                      { required: true, message: '请选择数据源' },
                    ]}
                    label="数据源"
                  >
                    <Select
                      showSearch
                      autoComplete="off"
                      placeholder="请选择数据源"
                      onChange={(val) => {
                        this.changeSourceType(val, index)
                        this.resultForm?.current?.setFieldsValue({
                          [`topic[${index}]`]: undefined,
                        })
                        this.resultForm?.current?.setFieldsValue({
                          [`tableName[${index}]`]: undefined,
                        })
                      }}
                      filterOption={(input, option) => option.props.title
                        .toLowerCase()
                        .indexOf(input.toLowerCase()) >= 0}
                    >
                      {(
                        (allValues[`sourceType[${index}]`]
                          ? this.state[`dataSources${allValues[`sourceType[${index}]`]}`]
                          : dataSourcesKafka) || []
                      ).map((o) => (
                        <Option
                          key={o.dsId}
                          value={o.dsId}
                          title={`${o.dsName}（${o.dsType}）`}
                        >
                          <div className="source-name">
                            {`${o.dsName}（${o.dsType}）`}
                          </div>
                        </Option>
                      ))}
                    </Select>
                  </Form.Item>
                  {allValues[`sourceType[${index}]`] === 'Kafka' ? (
                    <Form.Item
                      className={styles.real_time_form_item_full}
                      label={
                        <span style={{ width: '100%' }}>
                          <span>Topic</span>
                          <span
                            className={styles.real_time_form_item_full_right}
                            onClick={() => {
                              this.previewKafkaData(
                                allValues[`dsId[${index}]`],
                                allValues[`topic[${index}]`],
                              )
                            }}
                          >
                            数据预览
                          </span>
                        </span>
                      }
                      name={`topic[${index}]`}
                      rules={[
                        { required: true, message: '请选择Topic' },
                      ]}
                    >
                      <Select
                        showSearch
                        autoComplete="off"
                        placeholder="请选择Topic"
                        filterOption={(inputValue, option) => (
                          option.props.children
                            .toUpperCase()
                            .indexOf(inputValue.toUpperCase()) !== -1
                        )}
                      >
                        {(
                          sourceTableData[index].topics || []
                        ).map((val) => (
                          <Option label={val} key={val} value={val}>
                            {val}
                          </Option>
                        ))}
                      </Select>
                    </Form.Item>
                  ) : (
                    <Form.Item
                      className={styles.real_time_form_item_full}
                      label={
                        <span style={{ width: '100%' }}>
                          <span>表</span>
                          <span
                            className={styles.real_time_form_item_full_right}
                            onClick={() => {
                              this.previewData(
                                allValues[`dsId[${index}]`],
                                allValues[`tableName[${index}]`],
                              )
                            }}
                          >
                            数据预览
                          </span>
                        </span>
                      }
                      name={`tableName[${index}]`}
                      rules={[
                        { required: true, message: '请选择表' },
                      ]}
                    >
                      <Select
                        showSearch
                        autoComplete="off"
                        placeholder="请选择表"
                        onChange={(value) => {
                          if (
                            ['MySQL', 'Oracle', 'Hive'].indexOf(allValues[`sourceType[${index}]`]) !== -1
                          ) {
                            this.getTableFields(
                              allValues[`dsId[${index}]`],
                              value,
                              index,
                              allValues[`sourceType[${index}]`],
                            )
                          } else if (allValues[`sourceType[${index}]`] === 'HBase') {
                            this.getHbaseColumnFamilyNames(
                              allValues.dsId[index],
                              value,
                              index,
                            )
                          } else {
                            sourceTableData[index].fields = null
                            this.setState({
                              sourceTableData: [
                                ...sourceTableData,
                              ],
                            })
                          }
                        }}
                        filterOption={(inputValue, option) => (
                          option.props.children
                            .toUpperCase()
                            .indexOf(inputValue.toUpperCase()) !== -1
                        )}
                      >
                        {(
                          sourceTableData[index].tableNames || []
                        ).map((o) => (
                          <Option
                            label={o.name}
                            key={o.name}
                            value={o.name}
                          >
                            {o.name}
                          </Option>
                        ))}
                      </Select>
                    </Form.Item>
                  )}
                  {allValues[`sourceType[${index}]`] !== 'Hive' ? (
                    <Form.Item
                      name={`mappingTableName[${index}]`}
                      rules={[
                        { required: true, message: '请输入映射表' },
                      ]}
                      label="映射表"
                    >
                      <Input
                        autoComplete="off"
                        placeholder="请输入映射表"
                      />
                    </Form.Item>
                  ) : null}
                  {allValues[`sourceType[${index}]`] === 'HBase' ? (
                    <Form.Item label="RowKey">
                      <div style={{ paddingLeft: '30px' }}>
                        <Form.Item
                          name={`rowKeyName[${index}]`}
                          rules={[
                            { required: true, message: '请输入字段' },
                          ]}
                          label="字段"
                        >
                          <Input
                            autoComplete="off"
                            placeholder="请输入字段"
                            onBlur={() => {
                              this.resultForm.current.setFieldsValue({
                                [`primaryFields[${index}]`]: undefined,
                              })
                            }}
                          />
                        </Form.Item>
                        <Form.Item
                          name={`rowKeyType[${index}]`}
                          rules={[
                            { required: true, message: '请输入字段类型' },
                          ]}
                          label="类型"
                        >
                          <Input
                            autoComplete="off"
                            placeholder="请输入字段类型"
                          />
                        </Form.Item>
                      </div>
                    </Form.Item>
                  ) : null}
                  {allValues[`sourceType[${index}]`] === 'HBase' ? (
                    <Form.Item
                      className={styles.real_time_form_item_full}
                      label={
                        <span style={{ width: '100%' }}>
                          <span>字段</span>
                        </span>
                      }
                    >
                      <Table
                        columns={[
                          {
                            title: '列族',
                            dataIndex: 'columnFamily',
                            key: 'columnFamily',
                          },
                          {
                            title: '操作',
                            dataIndex: 'operation',
                            key: 'operation',
                            render: (text, record) => (
                              <span className="table-operation">
                                <span
                                  onClick={() => {
                                    record.fields.push({
                                      field: '',
                                      type: '',
                                    })
                                    this.forceUpdate()
                                  }}
                                >
                                  添加
                                </span>
                              </span>
                            ),
                          },
                        ]}
                        expandedRowRender={(o) => {
                          const columns = [
                            {
                              title: '字段',
                              dataIndex: 'field',
                              key: 'field',
                              render: (text, record) => (
                                <Input
                                  onChange={(e) => {
                                    record.field = e.target.value
                                    this.forceUpdate()
                                  }}
                                  onBlur={() => {
                                    this.saveData()
                                  }}
                                  value={text}
                                />
                              ),
                            },
                            {
                              title: '类型',
                              dataIndex: 'type',
                              key: 'type',
                              render: (text, record) => (
                                <Input
                                  onChange={(e) => {
                                    record.type = e.target.value
                                    this.forceUpdate()
                                  }}
                                  onBlur={() => {
                                    this.saveData()
                                  }}
                                  value={text}
                                />
                              ),
                            },
                            {
                              title: '操作',
                              dataIndex: 'operation',
                              key: 'operation',
                              render: (text, record, k) => (
                                <span className="table-operation">
                                  <span
                                    onClick={() => {
                                      o.fields.splice(k, 1)
                                      this.forceUpdate()
                                      this.saveData()
                                    }}
                                  >
                                    删除
                                  </span>
                                </span>
                              ),
                            },
                          ]

                          return (
                            <Table
                              columns={columns}
                              dataSource={o.fields}
                              pagination={false}
                            />
                          )
                        }}
                        dataSource={item.columnFamily}
                        pagination={false}
                      />
                    </Form.Item>
                  ) : null}
                  {allValues[`sourceType[${index}]`] === 'Hive' ? (
                    <Form.Item
                      className={styles.real_time_form_item_full}
                      label={
                        <span style={{ width: '100%' }}>
                          <span>字段</span>
                        </span>
                      }
                    >
                      <ProTable
                        pagination={false}
                        columns={HiveColumns(index)}
                        dataSource={item.fieldList}
                      />
                    </Form.Item>
                  ) : (
                    <Form.Item
                      className={styles.real_time_form_item_full}
                      label={
                        <span style={{ width: '100%' }}>
                          <span>字段</span>
                          <span
                            className={styles.real_time_form_item_full_right}
                            onClick={() => {
                              this.addField(index)
                            }}
                          >
                            添加
                          </span>
                        </span>
                      }
                    >
                      <ProTable
                        pagination={false}
                        columns={kafkaColumns(index)}
                        dataSource={item.fieldList}
                      />
                    </Form.Item>
                  )}

                  {allValues[`sourceType[${index}]`] !== 'Kafka' && allValues[`sourceType[${index}]`] !== 'Hive' ? (
                    <>
                      <Form.Item
                        name={`dataMode[${index}]`}
                        rules={[
                          { required: true, message: '请选择更新模式' },
                        ]}
                        label="更新模式"
                      >
                        <Radio.Group>
                          <Radio value={0}>追加(append)</Radio>
                          <Radio value={1}>更新(upsert)</Radio>
                        </Radio.Group>
                      </Form.Item>
                      {allValues[`dataMode[${index}]`] === 1 ? (
                        <Form.Item
                          name={`primaryFields[${index}]`}
                          rules={[
                            { required: true, message: '请选择主键' },
                          ]}
                          label="主键"
                        >
                          <Select
                            mode="multiple"
                            autoComplete="off"
                            placeholder="请选择表"
                          >
                            {allValues[`sourceType[${index}]`] === 'HBase'
                              ? allValues[`rowKeyName[${index}]`]
                              && [allValues.rowKeyName[index]].map((value) => (
                                <Option
                                  label={value}
                                  key={value}
                                  value={value}
                                >
                                  {value}
                                </Option>
                              ))
                              : item.fieldList.map((o) => (
                                <Option
                                  label={o.field}
                                  key={o.field}
                                  value={o.field}
                                >
                                  {o.field}
                                </Option>
                              ))}
                          </Select>
                        </Form.Item>
                      ) : null}
                    </>
                  ) : null}
                </Panel>
              ))}
            </Collapse>
          ) : (
            <Empty
              className={styles.real_time_task_panel_empty}
              description={
                <span>
                  暂无结果表，请{' '}
                  <span
                    className={styles.empty_add}
                    onClick={() => {
                      this.addSourceTable()
                    }}
                  >
                    添加
                  </span>
                </span>
              }
            />
          )}
        </Form>
        <Modal
          destroyOnClose
          title="数据预览"
          visible={kafkaDataShow}
          onCancel={() => {
            this.setState({
              kafkaDataShow: false,
            })
          }}
          footer={null}
        >
          <Spin spinning={this.state.confirmLoading}>
            <div className="preview_data_box">
              {previewKafkaDatas && previewKafkaDatas.length ? (
                <Collapse>
                  {previewKafkaDatas && previewKafkaDatas.map((item, key) => (
                    <Panel
                      header={<p className="preview_data_box_p">{item}</p>}
                      key={key}
                    >
                      <TextArea
                        value={item}
                        autoSize={{ minRows: 3, maxRows: 5 }}
                      />
                    </Panel>
                  ))}
                </Collapse>
              ) : (
                <Empty
                  className="real-time-task-panel-empty"
                  description={<span>暂无数据</span>}
                />
              )}
            </div>
          </Spin>
        </Modal>
        <Modal
          destroyOnClose
          title="数据预览"
          visible={previewDataShow}
          onCancel={() => {
            this.setState({
              previewDataShow: false,
            })
          }}
          footer={null}
        >
          <Spin spinning={this.state.confirmLoading}>
            <div className="preview_data_box">
              <ProTable
                pagination={false}
                columns={previewDatas.columns}
                dataSource={previewDatas.data}
              />
            </div>
          </Spin>
        </Modal>
      </div>
    )
  }
}

class WrappedComponentRef extends PureComponent {
  render() {
    const { forwardedRef, ...rest } = this.props
    return (
      <Result ref={forwardedRef} {...rest} />
    )
  }
}

const IComponent = connect(({ realTimeScriptDev }) => ({ ...realTimeScriptDev }))(WrappedComponentRef)

export default forwardRef((props, ref) => <IComponent {...props} forwardedRef={ref} />)
